<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是vimscript一些基础知识和操作的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="xLV02-vimscript-10-折叠.md">
<meta property="og:url" content="https://sumumm.github.io/post/342d6586.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是vimscript一些基础知识和操作的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/1.gif">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/2.gif">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/3.gif">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/4.gif">
<meta property="article:published_time" content="2023-07-02T07:05:59.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:57.068Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="VIM">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/1.gif">


<link rel="canonical" href="https://sumumm.github.io/post/342d6586.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/342d6586.html","path":"post/342d6586.html","title":"xLV02-vimscript-10-折叠.md"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>xLV02-vimscript-10-折叠.md | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E4%BB%80%E4%B9%88%E6%98%AF%E6%8A%98%E5%8F%A0%EF%BC%9F"><span class="nav-text">一、什么是折叠？</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%8A%98%E5%8F%A0%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="nav-text">1. 折叠的概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E4%B8%80%E4%B8%AA%E4%BE%8B%E5%AD%90"><span class="nav-text">2. 一个例子</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95"><span class="nav-text">二、基本语法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%8A%98%E5%8F%A0%E7%9A%84%E9%80%89%E9%A1%B9"><span class="nav-text">1. 折叠的选项</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-foldcolumn"><span class="nav-text">1.1 foldcolumn</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-foldlevel"><span class="nav-text">1.2 foldlevel</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-foldtext"><span class="nav-text">1.3 foldtext</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E6%8A%98%E5%8F%A0%E7%9A%84%E5%91%BD%E4%BB%A4"><span class="nav-text">2. 折叠的命令</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E5%88%9B%E5%BB%BA%E5%92%8C%E5%88%A0%E9%99%A4"><span class="nav-text">2.1 创建和删除</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E6%89%93%E5%BC%80%E5%92%8C%E5%85%B3%E9%97%AD"><span class="nav-text">2.2 打开和关闭</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-%E5%AD%98%E5%82%A8%E5%92%8C%E6%81%A2%E5%A4%8D"><span class="nav-text">2.3 存储和恢复</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E6%89%8B%E5%8A%A8%E6%8A%98%E5%8F%A0"><span class="nav-text">3. 手动折叠</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E6%8C%89%E7%BC%A9%E8%BF%9B%E6%8A%98%E5%8F%A0"><span class="nav-text">4. 按缩进折叠</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-%E6%8A%98%E5%8F%A0%E5%8E%9F%E7%90%86"><span class="nav-text">4.1 折叠原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2%E4%B8%80%E4%B8%AA%E5%AE%9E%E4%BE%8B"><span class="nav-text">4.2一个实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E6%8C%89%E6%A0%87%E5%BF%97%E6%8A%98%E5%8F%A0"><span class="nav-text">5. 按标志折叠</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1%E4%B8%80%E8%88%AC%E6%A0%BC%E5%BC%8F"><span class="nav-text">5.1一般格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2%E4%B8%80%E4%B8%AA%E5%AE%9E%E4%BE%8B"><span class="nav-text">5.2一个实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E6%8C%89%E8%AF%AD%E6%B3%95%E6%8A%98%E5%8F%A0"><span class="nav-text">6. 按语法折叠</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-%E6%8C%89%E6%98%AF%E5%90%A6%E6%94%B9%E5%8A%A8%E6%8A%98%E5%8F%A0"><span class="nav-text">7. 按是否改动折叠</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%8A%98%E5%8F%A0"><span class="nav-text">8. 表达式折叠</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E7%BB%BC%E5%90%88%E5%BA%94%E7%94%A8"><span class="nav-text">三、综合应用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%80%8E%E6%A0%B7%E7%9A%84%E6%95%88%E6%9E%9C%EF%BC%9F"><span class="nav-text">1. 怎样的效果？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E6%8C%89%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%8A%98%E5%8F%A0"><span class="nav-text">2. 按表达式折叠</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E7%89%B9%E6%AE%8A%E8%A1%8C%E6%8A%98%E5%8F%A0"><span class="nav-text">3. 特殊行折叠</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E7%A9%BA%E8%A1%8C%E5%A4%84%E7%90%86"><span class="nav-text">4. 空行处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E7%BC%A9%E8%BF%9B%E7%AD%89%E7%BA%A7"><span class="nav-text">5. 缩进等级</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E6%9C%80%E5%90%8E%E7%9A%84%E6%8A%98%E5%8F%A0%E5%87%BD%E6%95%B0"><span class="nav-text">6. 最后的折叠函数</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/342d6586.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="xLV02-vimscript-10-折叠.md | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          xLV02-vimscript-10-折叠.md
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-07-02 15:05:59" itemprop="dateCreated datePublished" datetime="2023-07-02T15:05:59+08:00">2023-07-02</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/" itemprop="url" rel="index"><span itemprop="name">开发工具</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/" itemprop="url" rel="index"><span itemprop="name">02VIM编辑器</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>7.2k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>26 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是vimscript一些基础知识和操作的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr><td align="center">参考方向  </td><td align="center">参考原文</td></tr>    <tr>        <td align="left">Learn vimscript the Hard Way</td>        <td align="left"><a href="https://learnvimscriptthehardway.stevelosh.com/" target="_blank">https://learnvimscriptthehardway.stevelosh.com/  <i class="fa fa-external-link-alt"></i> </a></td>      </tr>    <tr>        <td align="left">vim在线文档</td>        <td align="left"><a href="http://vimcdoc.sourceforge.net/" target="_blank">http://vimcdoc.sourceforge.net/  <i class="fa fa-external-link-alt"></i> </a></td>      </tr>    <tr>        <td align="left">VIM 中文帮助</td>        <td align="left"><a href="https://vimcdoc.sourceforge.net/doc/help.html" target="_blank">https://vimcdoc.sourceforge.net/doc/help.html  <i class="fa fa-external-link-alt"></i> </a></td>      </tr>    <tr>        <td align="left">vim教程</td>        <td align="left"><a href="https://www.w3cschool.cn/vim/" target="_blank">https://www.w3cschool.cn/vim/  <i class="fa fa-external-link-alt"></i> </a></td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center">---</td>        <td align="left">--- <a href="" target="_blank">  <i class="fa fa-external-link-alt"></i></a></td>      </tr></table>
              </div>
            </details>

<h1 id="一、什么是折叠？"><a href="#一、什么是折叠？" class="headerlink" title="一、什么是折叠？"></a><font size=3>一、什么是折叠？</font></h1><h2 id="1-折叠的概念"><a href="#1-折叠的概念" class="headerlink" title="1. 折叠的概念"></a><font size=3>1. 折叠的概念</font></h2><p>标题会是我看到这篇文章总标题想到的第一个问题，折叠就是叠起来嘛。那<code>Vim</code>文档中有两节来讲折叠：</p>
<table>
    <tr>
        <td align="center" width=200>VIM: usr_28</td>
        <td align="left"><a href="http://vimcdoc.sourceforge.net/doc/usr_28.html#usr_28.txt" target="_blank">usr_28.txt <i class="fa fa-external-link-alt"></i> </a></td>  
    </tr>
    <tr>
        <td align="center" width=200>VIM: fold</td>
        <td align="left"><a href="http://vimcdoc.sourceforge.net/doc/usr_28.html#usr_28.txt" target="_blank">fold.txt  <i class="fa fa-external-link-alt"></i> </a></td>  
    </tr>
</table>


<p>在一些<code>IDE</code>中都会有这样的折叠功能，其实就是这个样子的：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/1.gif" alt="动画" style="zoom: 50%;" />

<p><code>Vim</code>中折叠用于把缓冲区内某一范围内的文本行显示为屏幕上的一行。那些文本仍然在缓冲区内而没有改变。受到折叠影响的只是文本行显示的方式。 折叠的好处是，通过把多行的一节折叠成带有折叠提示的一行，会使我们更好地了解对文本的宏观结构。<code>Vim</code>支持六种不同折叠类型分别是<code>Manual</code>、<code>Marker</code>、<code>Diff</code>、<code>Expr</code>和<code>Indent</code>。</p>
<table>
    <tr><td align="center" width=100px>manual</td><td align="left">手动定义折叠</td></tr>
    <tr><td align="center" width=100px>indent</td><td align="left">更多的缩进表示更高级别的折叠</td></tr>
    <tr><td align="center" width=100px>expr</td><td align="left">用表达式来定义折叠</td></tr>
    <tr><td align="center" width=100px>syntax</td><td align="left">用语法高亮来定义折叠</td></tr>
    <tr><td align="center" width=100px>diff</td><td align="left">对没有更改的文本进行折叠</td></tr>
    <tr><td align="center" width=100px>marker</td><td align="left">对文中的标志折叠</td></tr>
</table>


<p>下边就来详细了解下吧！不过之前需要创建一个测试文件<code>test.vim</code>。</p>
<details class="folding-tag" blue><summary> 点击查看文件内容 </summary>
              <div class='content'>
              <figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">let num = 1</span><br><span class="line">let sum = 0</span><br><span class="line"></span><br><span class="line">while num &lt;= 10</span><br><span class="line">	let sum += num</span><br><span class="line">	let num += 1</span><br><span class="line">endwhile</span><br><span class="line"></span><br><span class="line">echo &quot;sum=&quot;sum&quot;\nnum=&quot;num</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="2-一个例子"><a href="#2-一个例子" class="headerlink" title="2. 一个例子"></a><font size=3>2. 一个例子</font></h2><p>我们可以将光标置于<code>while</code>所在的第四行，然后按下<code>zfap</code>四个按键，如下图所示：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/2.gif" style="zoom:50%;" />

<p>然后我们退出编辑器再打开看看，会发现这个折叠没有了。</p>
<details class="folding-tag" blue><summary> zfap啥意思？ </summary>
              <div class='content'>
              <figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">zf  是个操作符，代表创建折叠</span><br><span class="line">ap  是一个文本对象,代表&quot;一个段落&quot;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h1 id="二、基本语法"><a href="#二、基本语法" class="headerlink" title="二、基本语法"></a><font size=3>二、基本语法</font></h1><h2 id="1-折叠的选项"><a href="#1-折叠的选项" class="headerlink" title="1. 折叠的选项"></a><font size=3>1. 折叠的选项</font></h2><p>这里只列自己常用的几个，详细的可以使用<code>:help fold</code>来查看<code>Vim</code>中的手册，或者看这里：<a target="_blank" rel="noopener" href="http://vimcdoc.sourceforge.net/doc/fold.html#fold-options">VIM: fold.txt-fold-options   <i class="fa fa-external-link-alt"></i></a></p>
<h3 id="1-1-foldcolumn"><a href="#1-1-foldcolumn" class="headerlink" title="1.1 foldcolumn"></a><font size=3>1.1 <code>foldcolumn</code></font></h3><p>键值选项，设置在窗口的边上表示折叠的栏的宽度。当为 <code>0</code> 时，没有 折叠栏。值得范围最大为<code>12</code>，一般设置为<code>4</code>或者<code>5</code>，我一般设置为<code>2</code>。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">打开的折叠显示样式</span></span><br><span class="line">—</span><br><span class="line">|</span><br><span class="line">|</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">关闭的折叠显示样式</span></span><br><span class="line">+</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">折叠栏太窄不能显示所有折叠时，会显示一个数字来表示嵌套的级别</span></span><br></pre></td></tr></table></figure>

<p>若是设置了<code>mouse = a</code>也就是启用鼠标选项，就可以直接点击<code>+</code>来打开折叠，点击<code>-</code>来关闭折叠。、</p>
<h3 id="1-2-foldlevel"><a href="#1-2-foldlevel" class="headerlink" title="1.2 foldlevel"></a><font size=3>1.2 <code>foldlevel</code></font></h3><p>键值选项，数字越大则打开的折叠越多。为<code>0</code>时关闭所有折叠。</p>
<h3 id="1-3-foldtext"><a href="#1-3-foldtext" class="headerlink" title="1.3 foldtext"></a><font size=3>1.3 <code>foldtext</code></font></h3><p>键值选项，值是一个字符串。字符串可以是一个表达式，这个表达式被用来求得关闭折叠所显示的文字。</p>
<details class="folding-tag" blue><summary> 点击查看可以使用的变量 </summary>
              <div class='content'>
              <table>    <tr><td align="center" width=150px>v:foldstart</td><td align="left">折叠首行的行号</td></tr>    <tr><td align="center" width=150px>v:foldend</td><td align="left">折叠末行的行号</td></tr>    <tr><td align="center" width=150px>v:folddashes</td><td align="left">一个含有连字符的字符串，用来表示折叠级别</td></tr>    <tr><td align="center" width=150px>v:foldlevel</td><td align="left">折叠级别</td></tr></table>
              </div>
            </details>

<p>【注意】对 <code>:set</code> 命令作特殊处理的字符在其前面须加上反斜杠。如: 空格，反斜杠 和双引号。</p>
<p>键值选项，值为字符串，表示当前折叠方式。可以为<code>manual</code>、<code>indent</code>、<code>expr</code>、<code>marker</code>、<code>syntax</code>或者<code>diff</code>分别代表六种方式。</p>
<h2 id="2-折叠的命令"><a href="#2-折叠的命令" class="headerlink" title="2. 折叠的命令"></a><font size=3>2. 折叠的命令</font></h2><h3 id="2-1-创建和删除"><a href="#2-1-创建和删除" class="headerlink" title="2.1 创建和删除"></a><font size=3>2.1 创建和删除</font></h3><table>
    <tr><td align="center" width=150px>zf{motion}<br>或<br>{Visual}zf</td><td align="left">创建折叠操作符。仅当 'foldmethod' 设为 "manual" 或 "marker" 时有效。用 "manual" 方式，新建的折叠会被关闭。同时 'foldenable' 会被设定。</td></tr>
    <tr><td align="center" width=150px>zF</td><td align="left">对 [count] 行创建折叠。其余同 "zf" 。</td></tr>
    <tr><td align="center" width=150px>:{range}fo[ld]</td><td align="left">对 {range} 内的行创建折叠。其余同 "zf" 。</td></tr>
    <tr><td align="center" width=150px>zd</td><td align="left">删除 (delete) 在光标下的折叠。当光标在被折叠的行上，该折叠被删除。嵌套的折叠上移一级。在可视模式下所选区域 (部分) 涵盖的一层折叠被删除。仅当 'foldmethod' 设为 "manual" 或 "marker" 时有效。</td></tr>     
    <tr><td align="center" width=150px>zD</td><td align="left">循环删除 (Delete) 光标下的折叠。在可视模式下所选区域 (部分) 涵盖的折叠和嵌套的折叠都被删除。仅当 'foldmethod' 设为 "manual" 或 "marker" 时有效。</td></tr>
    <tr><td align="center" width=150px>zE</td><td align="left">除去 (Eliminate) 窗口里所有的折叠。仅当 'foldmethod' 设为 "manual" 或 "marker" 时有效。</td></tr>
</table>


<h3 id="2-2-打开和关闭"><a href="#2-2-打开和关闭" class="headerlink" title="2.2 打开和关闭"></a><font size=3>2.2 打开和关闭</font></h3><table>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zo" target="_blank">zo  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">打开 (open) 在光标下的折叠。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zO" target="_blank">zO  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">循环打开 (Open) 光标下的折叠。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zc" target="_blank">zc  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">关闭 (close) 在光标下的折叠。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zC" target="_blank">zC  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">循环关闭 (Close) 在光标下的所有折叠。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#za" target="_blank">za  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">打开关闭的折叠，或关闭打开的折叠。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zA" target="_blank">zA  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">当处在一关闭的折叠上时，循环地打开折叠。当处在一打开的折叠上时，循环地关闭折叠且设定 'foldenable'。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zv" target="_blank">zv  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">查看 (view) 光标所在的行: 仅打开足够的折叠使光标所在的行不被折叠。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zx" target="_blank">zx  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">重新应用 'foldlevel' 然后执行 "zv"。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zX" target="_blank">zX  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">手工恢复被打开和关闭的折叠: 再次应用 'foldlevel'。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zm" target="_blank">zm  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">折起更多 (more): 'foldlevel' 减 v:count1。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zM" target="_blank">zM  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">关闭所有折叠: 'foldlevel' 设为 0。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zr" target="_blank">zr  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">减少 (reduce) 折叠: 'foldlevel' 加 v:count1。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zR" target="_blank">zR  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">打开所有的折叠。'foldlevel' 设为最高级别。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zn" target="_blank">zn  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">不折叠 (none): 复位 'foldenable'。所有的折叠被打开。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zN" target="_blank">zN  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">正常折叠 (normal): 设定 'foldenable'。所有的折叠都展现它们之前的样子。</td></tr>
    <tr><td align="center" width=150px><a href="http://vimcdoc.sourceforge.net/doc/fold.html#zi" target="_blank">zi  <i class="fa fa-external-link-alt"></i> </a></td><td align="left">翻转 'foldenable' 的值。</td></tr>
</table>


<h3 id="2-3-存储和恢复"><a href="#2-3-存储和恢复" class="headerlink" title="2.3 存储和恢复"></a><font size=3>2.3 存储和恢复</font></h3><p>当我们关闭一个文件，开始编辑另一个文件时，被关闭的折叠状态就丢失了。如果稍后再重新打开关闭的文件，那么，所有手动打开和关闭的折叠，全都恢复到它们的默认状态了。如果折叠是用手动方式创建的，则所有的折叠都会消失。那这怎么解决呢？</p>
<table>
    <tr>
        <td align="center" width=100px><a href="http://vimcdoc.sourceforge.net/doc/starting.html#:mkview" target="_blank">:mkview  <i class="fa fa-external-link-alt"></i> </a></td>
        <td align="left">储存影响文件视图的设定及其它内容。</td>
    </tr>
    <tr>
        <td align="center" width=100px><a href="http://vimcdoc.sourceforge.net/doc/starting.html#:loadview" target="_blank">:loadview  <i class="fa fa-external-link-alt"></i> </a></td>
        <td align="left">可以重新载入前边保存的视图。</td>
    </tr>
</table>


<h2 id="3-手动折叠"><a href="#3-手动折叠" class="headerlink" title="3. 手动折叠"></a><font size=3>3. 手动折叠</font></h2><p>使用命令来手动定义要折叠的范围。但是该种方式创建的折叠在关闭文件后就会消失，要想留存的话可以使用存储的命令，在退出前存储视图，而后再载入视图即可。例如，在<code>mormal</code>模式下键入<code>zfap</code>便可以为一个文本段创建折叠。</p>
<h2 id="4-按缩进折叠"><a href="#4-按缩进折叠" class="headerlink" title="4. 按缩进折叠"></a><font size=3>4. 按缩进折叠</font></h2><p>由缩进行自动定义折叠。折叠级别由行的缩进除以<code>shiftwidth</code>(向下取整) 计算而得。连续的，有同样或更高的折叠级别的行，将会形成一个折叠。其中，有更高折叠级别的行形成嵌套的折叠。嵌套的级别数受 <code>foldnestmax</code> 选项限制。</p>
<p>某些行会被忽略并得到上一行或下一行的折叠级别 (取较小值)。符合条件的这样的行要么是空行，要么以 <code>foldignore</code>选项里包含的字符开始。在查找<code>foldignore</code> 里包含的字符时，空白字符会被忽略。对于 <code>C</code>语言，该选项使用 <code>#</code>来略过要预处理的那些行。</p>
<p>使用之前需要先设定<code>:set foldmethod=indent</code>。</p>
<h3 id="4-1-折叠原理"><a href="#4-1-折叠原理" class="headerlink" title="4.1 折叠原理"></a><font size=3>4.1 折叠原理</font></h3><p>大概的原理就是下边这样：</p>
<ul>
<li>文件中的每行代码都有一个<code>foldlevel</code>，它不是为零就是一个正整数。</li>
<li><code>foldlevel</code>为<code>0</code>的行不会被折叠。</li>
<li>有同等级的相邻行会被折叠到一起。</li>
<li>如果一个等级<code>n</code>的折叠被关闭了，任何在里面的、<code>foldlevel</code>不小于<code>n</code>的行都会一起被折叠，直到有一行的等级小于<code>n</code>。</li>
</ul>
<p>看完之后，模棱两可，说实话，反正我是没看懂，不过可以试验一下。</p>
<h3 id="4-2一个实例"><a href="#4-2一个实例" class="headerlink" title="4.2一个实例"></a><font size=3>4.2一个实例</font></h3><p>我们修改<code>test.vim</code>内容如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a1</span><br><span class="line">        b1</span><br><span class="line">        b2</span><br><span class="line">                c1</span><br><span class="line">                c2</span><br><span class="line">        b3</span><br><span class="line">a2</span><br></pre></td></tr></table></figure>

<p>然后在命令模式中执行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:set foldmethod=indent</span><br></pre></td></tr></table></figure>

<p>可以观察到以下现象：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/3.gif" alt="3" style="zoom:50%;" />

<p>然后我们在命令模式下依次执行以下命令观察输出结果：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">:echom <span class="title function_">foldlevel</span><span class="params">(<span class="number">1</span>)</span></span><br><span class="line">:echom <span class="title function_">foldlevel</span><span class="params">(<span class="number">2</span>)</span></span><br><span class="line">:echom <span class="title function_">foldlevel</span><span class="params">(<span class="number">3</span>)</span></span><br><span class="line">:echom <span class="title function_">foldlevel</span><span class="params">(<span class="number">4</span>)</span></span><br><span class="line">:echom <span class="title function_">foldlevel</span><span class="params">(<span class="number">5</span>)</span></span><br><span class="line">:echom <span class="title function_">foldlevel</span><span class="params">(<span class="number">6</span>)</span></span><br><span class="line">:echom <span class="title function_">foldlevel</span><span class="params">(<span class="number">7</span>)</span>     </span><br></pre></td></tr></table></figure>

<p>会依次看到有如下数字信息输出：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">0 1 1 2 2 1 0</span><br></pre></td></tr></table></figure>

<p>即有如下关系：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">a1                    foldlevel=0</span><br><span class="line">        b1            foldlevel=1</span><br><span class="line">        b2            foldlevel=1</span><br><span class="line">                c1    foldlevel=2</span><br><span class="line">                c2    foldlevel=2</span><br><span class="line">        b3            foldlevel=1</span><br><span class="line">a2                    foldlevel=0</span><br></pre></td></tr></table></figure>

<p>现在再去读上边的原理可能就更容易理解了。</p>
<h2 id="5-按标志折叠"><a href="#5-按标志折叠" class="headerlink" title="5. 按标志折叠"></a><font size=3>5. 按标志折叠</font></h2><h3 id="5-1一般格式"><a href="#5-1一般格式" class="headerlink" title="5.1一般格式"></a><font size=3>5.1一般格式</font></h3><p>标志用于指定一个折叠区的起点和终点。标志折叠可以精确地控制一个折叠究竟包含哪些行文本，缺点是需要改动文本。选项<code>foldtext</code>通常设 置为使折叠行显示折叠标志之前的文本，这样做可以为折叠命名。使用前需要设置选项<code>:set foldmethod=marker</code>。</p>
<p>标志可以包含级别数，也可以使用匹配对。包含级别数较简单，我们可以无须添加结束标志，并可以避免标志不配对的问题。一般格式如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">1.无结束标志</span></span><br><span class="line">&#123;&#123;&#123;n &quot; n表示级别</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">2.有结束标志</span></span><br><span class="line">&#123;&#123;&#123;n</span><br><span class="line">&#125;&#125;&#125;n</span><br></pre></td></tr></table></figure>

<p>（1）如果遇到级别相同的标志，上一个折叠结束，另一个有同样级别的折叠开始。</p>
<p>（2）如果遇到级别更高的标志，开始一个嵌套的折叠。 </p>
<p>（3）如果遇到级别更低的标志，所有大于或等于当前级别的折叠结束，且指定级别的折叠开始。</p>
<p>（4）带数字的标志和没有带数字的标志可以混合使用。但是<strong>一般建议带上结束标志和数字</strong>，这样更安全些。</p>
<p>【注意】</p>
<p>（1）数字指定了折叠级别。不能使用 <code>0</code> (忽略级别为 <code>0</code> 的标志)。</p>
<p>（2）对于一些编程语言源文件，这样做明显会报错，但是<code>Vim</code>是支持将其写在注释中的。</p>
<h3 id="5-2一个实例"><a href="#5-2一个实例" class="headerlink" title="5.2一个实例"></a><font size=3>5.2一个实例</font></h3><p>修改<code>test.vim</code>文件内容如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">/* global variables &#123;&#123;&#123;1 */</span><br><span class="line">        int varA, varB;</span><br><span class="line">/* functions &#123;&#123;&#123;1 */</span><br><span class="line">        /* funcA() &#123;&#123;&#123;2 */</span><br><span class="line">        void funcA() &#123;&#125;</span><br><span class="line"></span><br><span class="line">        /* funcB() &#123;&#123;&#123;2 */</span><br><span class="line">        void funcB() &#123;&#125;</span><br></pre></td></tr></table></figure>

<p>然后在命令模式下执行：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:<span class="built_in">set</span> foldmethod=marker</span><br></pre></td></tr></table></figure>

<p>会看到如下现象：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/02%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/02VIM%E7%BC%96%E8%BE%91%E5%99%A8/LV02-vimscript-10-%E6%8A%98%E5%8F%A0/img/4.gif" alt="4" style="zoom:50%;" />

<h2 id="6-按语法折叠"><a href="#6-按语法折叠" class="headerlink" title="6. 按语法折叠"></a><font size=3>6. 按语法折叠</font></h2><p><code>Vim</code> 为每一种不同的语言使用一个不同的语法文件。语法文件为文件中各种不同语法项定义颜色。如果我们正在用<code>Vim</code>在一个支持色彩的终端上阅读英文原版帮助文档，那么我们看见的色彩就是由语法文件<code>help</code>定制的。   在语法文件中，可以加入一些带有<code>fold</code> 参数的语法项来定义折叠，折叠级别由嵌套的折叠层数来定义。嵌套数由 <code>foldnestmax</code>限定。。这些语法项将定义折叠区。这要求写一个语法文件，把这些项目加入其中，然后可以像以上解释过的那样打开和关闭折叠，编辑文件时折叠会自动创建和删除。</p>
<h2 id="7-按是否改动折叠"><a href="#7-按是否改动折叠" class="headerlink" title="7. 按是否改动折叠"></a><font size=3>7. 按是否改动折叠</font></h2><p>对没有改动的文本或靠近改动的文本自动定义折叠。这个方法仅适用于当前窗口设定 <code>diff</code>选项来显示不同之处时才有效，否则，整个缓冲 区就是一个大的折叠。选项 <code>diffopt</code> 可以指定上下文，即折叠和不被折叠包括的改变之间相距的行数。例如，设定上下文为 <code>8</code>（默认值是 <code>6</code>）</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:set diffopt=filler,context:8</span><br></pre></td></tr></table></figure>

<p>当设定了 <code>scrollbind</code> 选项时，<code>Vim</code> 会试图在其它比较窗口中打开相同的折叠，这样这些窗口就会显示同一处文本。不需要讨论这种折叠就可以，因为<code>Vim</code>会自动使用它。</p>
<h2 id="8-表达式折叠"><a href="#8-表达式折叠" class="headerlink" title="8. 表达式折叠"></a><font size=3>8. 表达式折叠</font></h2><p>表达式折叠类似于缩进折叠，但并非利用文本行的缩进，对每行，通过计算选项 <code>foldexpr</code>的值（表达式）来并得到它的折叠级别，当表达式变得相对复杂时，可以将其放入一个函数，然后设定 <code>foldexpr</code>来调用该函数。表达式方式的折叠也是由折叠级别自动定义的。</p>
<p>【说明】</p>
<p>（1）表达式必须没有副作用。在缓冲区里的文字，光标位置，查找模式，选项等等，不能被改动。</p>
<p>（2）表达式中有错误或者计算结果不能识别时，<code>Vim</code> 不会产生错误消息，而是将折叠级别设为 <code>0</code>。所以当需要调试时，可将 <code>debug</code>选项设为 <code>msg</code>，错误消息就可以被见到了。</p>
<p>（3）最好避免使用 <code>=</code>，<code>a</code>和<code>s</code> 作为返回值，因为 <code>Vim</code> 不得不经常向后回溯以得到折叠级别，这会降低执行速度。</p>
<p>（4）<code>foldlevel()</code>计算相对于上一折叠级别的折叠级别。但要注意，如果该级别未知，<code>foidlevel()</code>将返回 <code>-1</code>。它返回的级别对应于该行开始的位置，尽管折叠本身可能在该行结束。 </p>
<p>（5）折叠可能会没有及时更新。用<code>zx</code>或者<code>zX</code>可以强制折叠更新。</p>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <p>对所有以制表符开始的连续的几行，创建折叠:</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:set foldexpr=getline(v:lnum)[0]==\&quot;\\t\&quot;</span><br></pre></td></tr></table></figure><p>调用函数来计算折叠级别:</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:set foldexpr=MyFoldLevel(v:lnum)</span><br></pre></td></tr></table></figure><p>用空白行分开的段落构成折叠:</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">:set foldexpr=getline(v:lnum)=~&#x27;^\\s*$&#x27;&amp;&amp;getline(v:lnum+1)=~&#x27;\\S&#x27;?&#x27;&lt;1&#x27;:1</span><br><span class="line">:set foldexpr=getline(v:lnum-1)=~&#x27;^\\s*$&#x27;&amp;&amp;getline(v:lnum)=~&#x27;\\S&#x27;?&#x27;&gt;1&#x27;:1</span><br></pre></td></tr></table></figure><p>【说明】变量 <code>v:lnum</code> 被定为该行行号</p><p>【注意】<code>:set</code> 要特殊处理的字符必须用反斜杠转义（空格，反斜杠，双引号等等）。</p>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看表达式计算结果说明 </summary>
              <div class='content'>
              <table>    <tr><td align="center" width=150px>值</td><td align="center">说明</td></tr>    <tr><td align="center" width=150px>0</td><td align="left">这行不折叠</td></tr>    <tr><td align="center" width=150px>1, 2, ..</td><td align="left">这行的折叠级别 1，2 等</td></tr>    <tr><td align="center" width=150px>-1</td><td align="left">折叠级别没有定义，使用这行之前或之后一行的级别值，取其中较小的一个。</td></tr>    <tr><td align="center" width=150px>"="</td><td align="left">使用上一行的折叠级别。</td></tr>    <tr><td align="center" width=150px>"a1", "a2", .. </td><td align="left">上一行的折叠级别加 1，2，..，结果适用于当前行</td></tr>    <tr><td align="center" width=150px>"s1", "s2", .. </td><td align="left">上一行的折叠级别减 1，2，..，结果适用于当前行</td></tr>    <tr><td align="center" width=150px>"&lt;1", "&lt;2", .. </td><td align="left">此折叠级别在本行结束</td></tr>    <tr><td align="center" width=150px>"&gt;1", "&gt;2", .. </td><td align="left">此折叠级别在本行开始</td></tr></table><p>【说明】不需要用<code>&gt;1</code> (<code>&lt;1</code>) 标志折叠的开始 (结束)，当这行折叠级别高于 (低于) 上一行的 级别时，折叠将开始 (结束)。</p>
              </div>
            </details>

<h1 id="三、综合应用"><a href="#三、综合应用" class="headerlink" title="三、综合应用"></a><font size=3>三、综合应用</font></h1><h2 id="1-怎样的效果？"><a href="#1-怎样的效果？" class="headerlink" title="1. 怎样的效果？"></a><font size=3>1. 怎样的效果？</font></h2><p>在之前，我们需要有想要折叠成的样子，然后才好动手，这个应用例子我想要达到的效果是这样的：</p>
<div class="tabs" id="tabname1"><ul class="nav-tabs"><li class="tab active"><a href="#tabname1-1">折叠前</a></li><li class="tab"><a href="#tabname1-2">折叠后</a></li></ul><div class="tab-content"><div class="tab-pane active" id="tabname1-1"><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">Hello</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> count = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;Hello World&quot;</span>);</span><br><span class="line">    <span class="keyword">for</span>(i = <span class="number">0</span>; i&lt;<span class="number">5</span>; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        count += i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;count=%d\n&quot;</span>, count)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">testHello</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    Hello();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div><div class="tab-pane" id="tabname1-2"><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">+--  11 lines: void Hello(void)</span><br><span class="line"></span><br><span class="line">+--  3 lines: void testHello(void)</span><br></pre></td></tr></table></figure></div></div></div>

<h2 id="2-按表达式折叠"><a href="#2-按表达式折叠" class="headerlink" title="2. 按表达式折叠"></a><font size=3>2. 按表达式折叠</font></h2><p>按表达式折叠的方式可以给我们最大限度的自由来自定义我们的折叠方式。修改<code>~/test.vim</code>文件，添加如下内容：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&quot; 设置侧边显示折叠栏宽度</span><br><span class="line">set foldcolumn = 2</span><br><span class="line">&quot; 告诉Vim使用expr折叠</span><br><span class="line">setlocal foldmethod=expr</span><br><span class="line">&quot; 计算折叠级别</span><br><span class="line">setlocal foldexpr=Get_C_fold(v:lnum)</span><br><span class="line"></span><br><span class="line">&quot; 对任意行均返回0的占位(dummy)函数</span><br><span class="line">function! Get_C_fold(lnum)</span><br><span class="line">    return &#x27;0&#x27;</span><br><span class="line">endfunction</span><br></pre></td></tr></table></figure>

<p>然后我们打开<code>test.c</code>文件，在<code>Vim</code>命令模式中执行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:source test.vim</span><br></pre></td></tr></table></figure>

<p>我们会发现仅仅左侧出现了折叠栏，然而并未有任何的折叠产生。这是因为函数对任意行均返回<code>0</code>,所以<code>Vim</code>将不会进行任何折叠。</p>
<h2 id="3-特殊行折叠"><a href="#3-特殊行折叠" class="headerlink" title="3. 特殊行折叠"></a><font size=3>3. 特殊行折叠</font></h2><p>自定义的表达式可以直接返回一个<code>foldlevel</code>，或者返回一个特殊字符串来告诉<code>Vim</code>如何折叠这一行。例如<code>&#39;-1&#39;</code>可以作为一种特殊字符串，它可以告诉<code>Vim</code>，这一行的<code>foldlevel</code>为<code>undefined</code>。 <code>Vim</code>将把它理解为：该行的<code>foldlevel</code>等于其上一行或下一行的较小的那个<code>foldlevel</code>。</p>
<p><code>Vim</code>可以把<code>undefined</code>的行串在一起，所以假设有三个<code>undefined</code>的行和接下来的一个<code>level1</code>的行， 它将设置最后一行为<code>1</code>，接着是倒数第二行为<code>1</code>，然后是第一行为<code>1</code>。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">undefined    1</span><br><span class="line">undefined    1</span><br><span class="line">undefined    1</span><br><span class="line">level 1      1</span><br></pre></td></tr></table></figure>

<h2 id="4-空行处理"><a href="#4-空行处理" class="headerlink" title="4. 空行处理"></a><font size=3>4. 空行处理</font></h2><p>修改<code>Get_C_fold</code>函数，加入空行处理功能，修改函数如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">function! Get_C_fold(lnum)</span><br><span class="line">    if getline(a:lnum) =~? &#x27;\v^\s*$&#x27;</span><br><span class="line">        return &#x27;-1&#x27;</span><br><span class="line">    endif</span><br><span class="line"></span><br><span class="line">    return &#x27;0&#x27;</span><br><span class="line">endfunction</span><br></pre></td></tr></table></figure>

<p>然后我们打开<code>test.c</code>文件，在<code>Vim</code>命令模式中执行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:source test.vim</span><br></pre></td></tr></table></figure>

<p>我们会发现仅仅左侧出现了折叠栏，然而还是未有任何的折叠产生。这是因为所有的行的<code>foldlevel</code>要不是为<code>0</code>，就是为<code>undefined</code>。 等级为<code>0</code>的行将影响<code>undefined</code>的行，最终导致所有的行的<code>foldlevel</code>都是<code>0</code>。</p>
<p>【说明】</p>
<p>（1）<code>\v^\s*$</code>是正则表达式，将匹配”行的开头，任何空白字符，行的结尾”。</p>
<p>（2）比较用大小写不敏感的比较符<code>=~?</code>完成，也可以使用<code>=~</code>只匹配正则表达式。</p>
<p>（3）如果当前行包括一些非空白字符，它将不会匹配，将如返回<code>&#39;0&#39;</code>。如果当前行匹配正则表达式(比如它是空的或者只有空格)，就返回字符串<code>&#39;-1&#39;</code>。</p>
<h2 id="5-缩进等级"><a href="#5-缩进等级" class="headerlink" title="5. 缩进等级"></a><font size=3>5. 缩进等级</font></h2><ul>
<li>函数一：获取各行缩进等级</li>
</ul>
<p>接下来就是缩进等级的处理了，主要是针对非空行的处理，我们在<code>test.vim</code>中新增一个函数：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function! Indent_level(lnum)</span><br><span class="line">    return indent(a:lnum) / &amp;shiftwidth</span><br><span class="line">endfunction</span><br></pre></td></tr></table></figure>

<details class="folding-tag" blue><summary> 点击查看 indent 函数 </summary>
              <div class='content'>
              <ul><li><code>indent({lnum})</code></li></ul><p>返回数值，表示第 <code>{lnum}</code> 行的缩进距离。缩进的计算以空格计，因此它与<code>tabstop</code>的值有关系。<code>{lnum}</code> 的使用方式和  <a target="_blank" rel="noopener" href="http://vimcdoc.sourceforge.net/doc/eval.html#getline()">getline()  <i class="fa fa-external-link-alt"></i></a>  相同。如果 <code>{lnum}</code> 非法，返回 <code>-1</code>，例如行号不存在的时候，就会返回<code>-1</code>。</p>
              </div>
            </details>

<p>然后我们在<code>test.c</code>文件窗口的吗，命令模式执行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:echom Indent_level(n)    </span><br></pre></td></tr></table></figure>

<p>将会显示第<code>n</code>行的缩进等级。</p>
<ul>
<li>函数二：获取下一个非空行行号</li>
</ul>
<p>为什么需要这样一个函数呢？主要是为了将折叠段头行到对应的缩进段中。在<code>test.vim</code>中增加如下函数：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">function! Next_noneblank_line(lnum)</span><br><span class="line">	&quot; 1.获取文件总行数</span><br><span class="line">    let numlines = line(&#x27;$&#x27;)</span><br><span class="line">    &quot; 2.设置current为下一行行号</span><br><span class="line">    let current = a:lnum + 1</span><br><span class="line">	&quot; 3.遍历当前行一直到文件最后一行，寻找首个非空行</span><br><span class="line">    while current &lt;= numlines</span><br><span class="line">        &quot; 匹配有一个非空白字符的行 \v\S表示非空白字符</span><br><span class="line">        if getline(current) =~? &#x27;\v\S&#x27;</span><br><span class="line">            return current</span><br><span class="line">        endif</span><br><span class="line">		</span><br><span class="line">        let current += 1</span><br><span class="line">    endwhile</span><br><span class="line"></span><br><span class="line">    return -2</span><br><span class="line">endfunction</span><br></pre></td></tr></table></figure>

<p>若是找到了非空行，就返回非空行行号，要是没有非空行，那就会一直向下循环，直到循环结束，都还是空白行的话，那么就返回<code>&#39;-2&#39;</code>，当遇到不存在的行的时候也是会返回<code>&#39;-2&#39;</code>。</p>
<p>那为什么不是<code>&#39;-1&#39;</code>或者<code>&#39;0&#39;</code>作为返回值呢？<code>&#39;-1&#39;</code>(和<code>&#39;0&#39;</code>)是特殊的<code>Vim foldlevel</code>选项字符串。看到<code>&#39;-1&#39;</code>，会想到上一个空行处理的返回结果含义为<code>undefined foldlevel</code>。 <code>&#39;0&#39;</code>也类似，会有其他不同的含义。 这里用一个其他的数值可以突出它不是一个<code>foldlevel</code>，而是表示一个错误。不过当然也可以返回<code>&#39;1&#39;</code>或者<code>&#39;0&#39;</code>，也不会有问题，区分清楚就可以啦。</p>
<h2 id="6-最后的折叠函数"><a href="#6-最后的折叠函数" class="headerlink" title="6. 最后的折叠函数"></a><font size=3>6. 最后的折叠函数</font></h2><p>前边对一些特殊情况和一般情况已经处理完毕了，接下来来就是最后的折叠函数，也就是表达式需要的折叠规则。在<code>test.vim</code>中修改函数<code>Get_C_fold</code>：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">function! Get_C_fold(lnum)</span><br><span class="line">	&quot; 1.空行处理</span><br><span class="line">    if getline(a:lnum) =~? &#x27;\v^\s*$&#x27;</span><br><span class="line">        return &#x27;-1&#x27;</span><br><span class="line">    endif</span><br><span class="line">	&quot; 2获取各行的缩进等级</span><br><span class="line">    let this_indent = Indent_level(a:lnum)</span><br><span class="line">    &quot; 3.获取当前行的下一行的缩进等级</span><br><span class="line">    let next_indent = Indent_level(Next_noneblank_line(a:lnum))</span><br><span class="line">	&quot; 4.同级缩进判断</span><br><span class="line">	&quot; 下一行缩进等级与当前行相等，则返回当前行缩进等级</span><br><span class="line">    if next_indent == this_indent    </span><br><span class="line">        return this_indent</span><br><span class="line">    &quot; 下一行缩进等级小于当前行，则返回当前行缩进等级</span><br><span class="line">    elseif next_indent &lt; this_indent </span><br><span class="line">        return this_indent</span><br><span class="line">    &quot; 下一行缩进等级大于当前行，则返回返回一个以 &gt;开头和下一行的缩进等级构成的字符串</span><br><span class="line">    elseif next_indent &gt; this_indent </span><br><span class="line">        return &#x27;&gt;&#x27; . next_indent</span><br><span class="line">    endif</span><br><span class="line">endfunction</span><br></pre></td></tr></table></figure>

<p>我们可以先试一下这个函数获取的每行的缩进等级是怎样的，我们可以在<code>test.c</code>中执行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:source test.vim</span><br></pre></td></tr></table></figure>

<p>这条命令可以使脚本文件在此窗口中生效，然后依次执行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:echo Get_C_fold(n)</span><br></pre></td></tr></table></figure>

<p>但是好像行数有点多哈，那我们来做一个测试函数把，在<code>test.vim</code>中添加以下测试函数：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function! Test()</span><br><span class="line">	let numlines = line(&#x27;$&#x27;)</span><br><span class="line">	let i = 1</span><br><span class="line">		while i &lt;= numlines</span><br><span class="line">			echo Get_C_fold(i)</span><br><span class="line">			let i += 1</span><br><span class="line">        endwhile</span><br><span class="line">endfunction</span><br></pre></td></tr></table></figure>

<p>然后在<code>test.c</code>中命令模式下执行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">:source test.vim</span><br><span class="line">:call Test()</span><br></pre></td></tr></table></figure>

<p>其实此时已经可以看到缩进效果了，不过这里主要还是分析缩进级别，这样便可以获取每一行的缩进级别，可以得到如下对应关系：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">Hello</span><span class="params">(<span class="type">void</span>)</span>                   <span class="comment">/* 0  */</span></span><br><span class="line">&#123;                                  <span class="comment">/* &gt;1 */</span></span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;                     <span class="comment">/* 1  */</span></span><br><span class="line">    <span class="type">int</span> count = <span class="number">0</span>;                 <span class="comment">/* 1  */</span></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;Hello World&quot;</span>);         <span class="comment">/* 1  */</span></span><br><span class="line">    <span class="keyword">for</span>(i = <span class="number">0</span>; i&lt;<span class="number">5</span>; i++)           <span class="comment">/* 1  */</span></span><br><span class="line">    &#123;                              <span class="comment">/* &gt;2 */</span></span><br><span class="line">        count += i;                <span class="comment">/* 2  */</span></span><br><span class="line">    &#125;                              <span class="comment">/* 1  */</span></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;count=%d\n&quot;</span>, count)    <span class="comment">/* 1  */</span></span><br><span class="line">&#125;                                  <span class="comment">/* 0  */</span></span><br><span class="line">								   <span class="comment">/* -1 */</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">testHello</span><span class="params">(<span class="type">void</span>)</span>               <span class="comment">/* 0  */</span></span><br><span class="line">&#123;                                  <span class="comment">/* &gt;1 */</span></span><br><span class="line">    Hello();                       <span class="comment">/* 1  */</span></span><br><span class="line">&#125;                                  <span class="comment">/* 0  */</span></span><br></pre></td></tr></table></figure>

<p>上边在表达式折叠中有提到，<code>&gt;n</code>就表示此折叠在本行开始，这就意味，这一行与下一行将折叠在一起。</p>
<details class="folding-tag" blue><summary> 最后一行？ </summary>
              <div class='content'>
              <p>其实一直以来都有一个问题哈，就是最后一行，我们并没有分析过，但是让人开心的是，它最后也得出了正确的折叠等级，但是究竟是为什么呢？</p><ul><li>情况一：</li></ul><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a1</span><br><span class="line">a2</span><br><span class="line">	b1</span><br><span class="line">		c1</span><br><span class="line">a3</span><br></pre></td></tr></table></figure><p>处理<code>a3</code>的时候，得到它的<code>this_indent = 0</code>，文件到这行已经结束了，那下一行呢？此时我们调用<code>Next_noneblank_line()</code>函数来获取下一个非空行行号时，函数发现下一行不存在，所以直接返回<code>&#39;-2&#39;</code>，在获取下一行缩进等级的时候做了一个除法操作，所以得到<code>next_indent = 0</code>，于是<code>this_indent  = next_indent </code>了，就返回了<code>&#39;0&#39;</code>。</p><ul><li>情况二：</li></ul><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a1</span><br><span class="line">a2</span><br><span class="line">	b1</span><br><span class="line">		c1</span><br></pre></td></tr></table></figure><p>现在<code>c1</code>作为最后一行，得到它的<code>this_indent = 2</code>，而下一行已经不存在了，所以会得到<code>next_indent = 0</code>，于是就有了<code>next_indent  &lt; this_indent</code>，此时会返回<code>&#39;2&#39;</code>。</p>
              </div>
            </details>

<p>然后，我们在<code>test.c</code>中命令模式下执行下边的命令使折叠生效：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">:source test.vim</span><br></pre></td></tr></table></figure>

<p>接着会发现，代码折叠成了这样：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">Hello</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">+--  9 lines: &#123;-----------------------------------------------------------</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">testHello</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">+--  2 lines: &#123;-----------------------------------------------------------</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>额，勉勉强强吧😂，折叠的目的达到了，但是由于花括号的独占一行，就是目前的样子了，后边还可以继续优化嘛😁。</p>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/342d6586.html">xLV02-vimscript-10-折叠.md</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2023年07月02日 - 15:05</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/342d6586.html" title="xLV02-vimscript-10-折叠.md">https://sumumm.github.io/post/342d6586.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/VIM/" rel="tag"><i class="fa fa-tag"></i> VIM</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/1231840e.html" rel="prev" title="LV01-Git-01-版本控制">
                  <i class="fa fa-angle-left"></i> LV01-Git-01-版本控制
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/5e07b64.html" rel="next" title="LV02-vimscript-09-插件.md">
                  LV02-vimscript-09-插件.md <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">false</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
